﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Data;

namespace DbManager
{
    /// <summary>
    /// 封装sql语句执行类
    /// </summary>
    public abstract class DbExcute : DbDataBase, IExcute
    {
        #region 公开的方法
        /// <summary>
        /// 抽象设置DbCommand属性字段方法
        /// </summary>
        /// <returns></returns>
        protected abstract DbCommand SetParameters();
        /// <summary>
        /// 执行数据库操作方法
        /// </summary>
        /// <returns></returns>
        public virtual bool Excute()
        {
            bool flag = false;
            //得到DbCommand对象
            DbCommand command = SetParameters();
            //得到事物
            DbTransaction dbTran = base.DbTran;
            try
            {
                flag = base.ExecuteUpdate(command, dbTran) > 0;
                //提交事务
                dbTran.Commit();
            }
            catch (Exception exception)
            {
                //回滚事务
                dbTran.Rollback();
                throw (exception);
            }
            finally
            {
                //关闭连接
                base.DbConnectionColse();
            }
            //返回结果
            return flag;
        }
        /// <summary>
        /// 执行带事物的数据库操作方法
        /// </summary>
        /// <param name="dbtr">事物</param>
        public virtual bool Excute(DbTransaction dbtr)
        {
            DbCommand command = SetParameters();
            return (base.ExecuteUpdate(command, dbtr) > 0);
        }
        /// <summary>
        /// 执行数据库操作方法(返回第一行第一列)
        /// </summary>
        /// <returns></returns>
        public virtual object ExecuteScalar()
        {
            object flag = null;
            //得到DbCommand对象
            DbCommand command = SetParameters();
            //得到事物
            DbTransaction dbTran = base.DbTran;
            try
            {
                flag = base.ExecuteScalar(command, dbTran);
                //提交事务
                dbTran.Commit();
            }
            catch (Exception exception)
            {
                //回滚事务
                dbTran.Rollback();
                throw (exception);
            }
            finally
            {
                //关闭连接
                base.DbConnectionColse();
            }
            //返回结果
            return flag;
        }
        /// <summary>
        /// 执行带事物的数据库操作方法
        /// </summary>
        /// <param name="dbtr">事物</param>
        public virtual object ExecuteScalar(DbTransaction dbtr)
        {
            DbCommand command = SetParameters();
            object flag = null;
            flag = base.ExecuteScalar(command, dbtr);
            return flag;
        }
        #endregion
    }
}
